layui.extend({
    com: 'lib/common'
    , request: 'lib/request'
    , staticData: 'lib/extend/staticData'
}).define(['form','com', 'request','staticData'], function (exports) {
    var $ = layui.jquery, form = layui.form,com = layui.com, request = layui.request, staticData = layui.staticData,
        loginType = 0,original = (com.getUrlParam('original') || '/manage.html#/'),
        $obtainSms = $('#obtainSms'),fn = {
            codeSeconds:60
            ,switchLogin: function (t) {
                loginType = t;
                $('[login-type]').hide();
                $('[login-type="' + t + '"]').show();
                if (loginType == '0') {
                    $('#userName').focus();
                } else if (loginType == '1') {
                    $('#phoneNo').focus();
                }
            }
            ,getSmsCode: function() {
                let $phoneNo = $('#phoneNo');
                if (com.isEmpty($phoneNo.val())) {
                    $phoneNo.focus();
                    layer.msg('请输入手机号');
                    return;
                }
                if (!com.reg.phone.test($phoneNo.val())) {
                    $phoneNo.focus();
                    layer.msg('请输入正确的手机号码');
                    return;
                }
                $obtainSms.attr({'disabled':true});
                request.post('/scm/auth/sendVerificationCode',{phoneNo:$phoneNo.val()}).then(res => {
                    layer.msg('发送成功');
                    com.setLocalStorage('$sendLoginMessageTime', moment().valueOf() / 1000);
                    fn.handleLoginMessageTime(59);
                }).catch(err => {
                    $obtainSms.attr({'disabled':null}).removeClass('layui-btn-disabled');
                });
            }
            ,handleLoginMessageTime: function(time) {
                let timer = setInterval(() => {
                    if (time === 0) {
                        clearInterval(timer);
                        $obtainSms.attr({'disabled':null}).html('获取短信验证码');
                    } else {
                        fn.codeSeconds = time;
                        $obtainSms.attr({'disabled':true}).html(fn.codeSeconds+'秒后再次发送');
                        time--;
                    }
                }, 1000);
            }
            ,slider: function () {
                //初始化验证码  弹出式
                $('#sliderCodePanel').slideVerify({
                    //baseUrl:'https://mirror.anji-plus.com/captcha-api',  //服务器请求地址, 默认地址为安吉服务器;
                    baseUrl: '/scm',
                    mode: 'pop',     //展示模式
                    containerId: 'login-btn',//pop模式 必填 被点击之后出现行为验证码的元素id
                    imgSize: {//图片的大小对象,有默认值{ width: '310px',height: '155px'},可省略
                        width: '400px',
                        height: '200px',
                    },
                    barSize: { //下方滑块的大小对象,有默认值{ width: '310px',height: '50px'},可省略
                        width: '400px',
                        height: '40px',
                    },
                    beforeCheck: function () {  //检验参数合法性的函数  mode ="pop"有效
                        let flag = true;
                        //实现: 参数合法性的判断逻辑, 返回一个boolean值
                        return flag
                    },
                    ready: function () {
                    },  //加载完毕的回调
                    success: function (params) { //成功的回调
                        // params为返回的二次验证参数 需要在接下来的实现逻辑回传服务器
                        // 例如: login($.extend({}, params))
                        $("#captchaVerification").val(params.captchaVerification);
                    },
                    error: function () { //失败的回调

                    }
                });
            }
            ,wxCode:''
            ,scanTimer:null
            ,wxLogin:function () {
                com.showLoading();
                fn.wxCode = com.uuid();
                request.postForm('/scm/wx/genTempQrcode',{'code':fn.wxCode}).then(res =>{
                    $('#wxQrCode').attr({'src':'https://mp.weixin.qq.com/cgi-bin/showqrcode?ticket='.concat(res.data)});
                    $('.account-login').hide();
                    $('.wx-login').show();
                    fn.startScan();
                });
            }
            ,backAccountLogin:function () {
                $('.wx-login').hide();
                $('.account-login').show();
                clearInterval(fn.scanTimer);
                fn.wxCode = "";
            }
            ,startScan:function () {
                fn.scanTimer = setInterval(function () {
                    clearInterval(fn.scanTimer);
                    if(com.isNotEmpty(fn.wxCode)){
                        request.send({
                            type: 'POST'
                            , contentType: 'application/json;charset=UTF-8'
                            , showLoading: false
                            , url: '/scm/auth/checkLogin'
                            , data: JSON.stringify({'bindAccessId':fn.wxCode,'roleType':'client'})
                        }).then(res =>{
                            let data = res.data;
                            if(data==null){
                                fn.startScan();
                            }else{
                                fn.judgeLogin(data);
                            }
                        });
                    }
                },1000);
            },
            judgeLogin(data){
                if(data.success){
                    com.setLocalStorageJson('$user', data);
                    staticData.clearAll();
                    layer.msg('登录成功');
                    setTimeout(function () {
                        if (original.startsWith('/')) {
                            location.href = '/manage.html#/';
                        } else {
                            location.href = original;
                        }
                    }, 1000);
                }else{
                    location.href = '/bind-account.html?bindAccessId='+data.bindAccessId;
                }
            }
        };
        // 已经登录自动进入管理界面
       if(JSON.stringify(com.getUser())!="{}"){
           location.href='/manage.html#/';
       }

    fn.switchLogin(com.getUrlParam('t') || 0);
    fn.slider();
    $('[switch-login-type]').click(function () {
        fn.switchLogin($(this).attr('switch-login-type'));
    });
    $obtainSms.click(function () {
        fn.getSmsCode();
    });
    form.verify({
        userName: function (value, item) {
            if (loginType == '0' && com.isEmpty(value)) {
                return '请输入登录账号';
            }
        }, passWord: function (value, item) {
            if (loginType == '0' && com.isEmpty(value)) {
                return '请输入登录密码';
            }
        }, phoneNo: function (value, item) {
            if (loginType == '1') {
                if (com.isEmpty(value)) {
                    return '请输入手机号';
                }
                if (!com.reg.phone.test(value)) {
                    return '请输入正确的手机号码';
                }
            }
        }, messageCode: function (value, item) {
            if (loginType == '1' && com.isEmpty(value)) {
                return '请输入短信验证码';
            }
        }
    });
    form.on('submit(login-btn)', function (data) {
        let params = $('#loginForm').serializeJson();
        let reqparams = $.extend({},params,{
            loginType:loginType,
            captchaVerification:$("#captchaVerification").val(),
            userName:(loginType == '0')?params.userName:params.phoneNo
        });
        request.post('/scm/auth/login', reqparams).then(res => {
            $("#sliderCodePanel").hide();
            com.setLocalStorage('$login',Base64.encode(JSON.stringify({'userName':params.userName,'passWord':params.passWord,'phoneNo':params.phoneNo})));
            fn.judgeLogin(res.data);
        }).catch(res => {
            if (res.code == '777003052' || res.code == '777003053' || res.code == '777003054') {
                $("#sliderCodePanel").show();
            } else {
                $("#sliderCodePanel").hide();
            }
        });
        return false;
    });
    let loginpar = com.getLocalStorage('$login');
    if(com.isNotEmpty(loginpar)){
        form.val('form-login',JSON.parse(Base64.decode(loginpar)));
    }
    //发送短信验证码计时器
    const time = moment().valueOf() / 1000 - com.getLocalStorage('$sendLoginMessageTime');
    if (time < 60) {
        fn.codeSeconds = fn.codeSeconds - parseInt(time, 10);
        fn.handleLoginMessageTime(fn.codeSeconds);
    }
    exports('login', fn);
});